<template>
  <div class="travel_price_operate">
    <el-form
      ref="baseDataFormRef"
      :model="baseData"
      :rules="rules"
      label-width="120px"
      :disabled="readOnly"
      class="base_details_form"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="单房差" prop="singleRoomPrice">
            <el-input-number
              v-model.number="baseData.singleRoomPrice"
              :min="0"
              :precision="2"
              :controls="false"
              controls-position="right"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最低成团人数">
            <el-input
              v-model="baseData.groupPeopleNum"
              type="number"
              onkeyup="value=value.replace(/^[^\d]+/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计划预收位">
            <el-input
              v-model="baseData.expectPeopleNum"
              type="number"
              onkeyup="value=value.replace(/^[^\d]+/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最低预定人数">
            <el-input
              v-model="baseData.packagePeopleNum"
              type="number"
              onkeyup="value=value.replace(/^[^\d]+/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最大预定人数">
            <el-input
              v-model="baseData.orderPeopleNum"
              type="number"
              onkeyup="value=value.replace(/^[^\d]+/g,'')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="套餐库存">
            <el-input
              v-model="baseData.stockNum"
              type="number"
              onkeyup="value=value.replace(/^[^\d]+/g,'')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <DynamicParams
      ref="priceTemplateRef"
      :template="priceTemplateTemplate"
      :data="priceTemplate"
      @add="addTemplate"
      :customDel="true"
      @delete="delTemplate"
      :customAdd="true"
      :operation="priceTemplateOperation"
      addText="添加价格类型"
    >
      <el-table-column label="价格类型" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.priceType" />
        </template>
      </el-table-column>
      <el-table-column label="是否占床" align="center" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.withBedFlag"
            inline-prompt
            active-text="占床"
            inactive-text="不占"
            :active-value="1"
            :inactive-value="0"
            size="large"
            :width="60"
          />
        </template>
      </el-table-column>
      <el-table-column label="同行价(元)" align="center" width="120">
        <template #default="scope">
          <el-input-number
            v-model.number="scope.row.competitorPrice"
            :min="0"
            :precision="2"
            :controls="false"
            controls-position="right"
          />
        </template>
      </el-table-column>
      <el-table-column label="销售价(元)" align="center" width="120">
        <template #default="scope">
          <el-input-number
            v-model.number="scope.row.sellPrice"
            :min="0"
            :precision="2"
            :controls="false"
            controls-position="right"
          />
        </template>
      </el-table-column>
      <el-table-column label="划线价(元)" align="center" width="120">
        <template #default="scope">
          <el-input-number
            v-model.number="scope.row.markingPrice"
            :min="0"
            :precision="2"
            :controls="false"
            controls-position="right"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="单房差" align="center" width="120">
        <template #default="scope">
          <el-input-number v-model.number="scope.row.singleRoomPrice" :min="0" :precision="2" :controls="false"
            controls-position="right" />
        </template>
      </el-table-column> -->
    </DynamicParams>
    <div class="operate_layout">
      <div class="operate_item">
        <div class="picker">
          <el-date-picker
            v-model="selectDate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            :shortcuts="pickerOptions"
            :disabled-date="disabledDate"
          />
        </div>
        <el-radio-group v-model="selectOperate">
          <el-radio v-for="item in operate" :key="item.id" :label="item.id"
            >{{ item.name }}
          </el-radio>
        </el-radio-group>
      </div>
      <div class="operate_item">
        <el-checkbox-group v-model="selectWeek">
          <el-checkbox v-for="item in weeks" :key="item.id" :label="item.id"
            >{{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
        <div>
          <el-switch
            class="calendar_switch"
            v-model="calendarSwitch"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #409eff;
            "
            active-text="6月"
            inactive-text="12月"
          />
          <el-button type="primary" @click="execute">批量执行</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import {
  ref,
  reactive,
  defineProps,
  defineExpose,
  defineEmits,
  watch,
} from "vue";
import msg from "@ui/message";
import DynamicParams from "@com/DynamicParams.vue";
const props = defineProps({
  readOnly: { type: Boolean, default: false },
});
const emit = defineEmits(["execute", "checkOperateChange", "calendarSwitch"]);

const baseDataFormRef = ref(null);
const baseData = reactive({
  singleRoomPrice: null,
  groupPeopleNum: null,
  expectPeopleNum: null,
  packagePeopleNum: null,
  stockNum: null,
  orderPeopleNum: null,
});

const rules = {
  singleRoomPrice: [
    {
      required: true,
      message: "请填写单房差",
      trigger: "blur",
    },
  ],
};

const chackBaseKey = [
  "groupPeopleNum",
  "expectPeopleNum",
  "packagePeopleNum",
  "stockNum",
  "orderPeopleNum",
];

const priceTemplateOperation = {
  move: false,
  modify: false,
  del: true,
  add: true,
  check: false,
};
const calendarSwitch = ref((localStorage.getItem("calendarNumber") || 6) == 6);
const priceTemplateRef = ref(null);
const priceTemplate = ref([
  // {
  //   priceType: "成人票",
  //   costPrice: 30,
  //   competitorPrice: 30,
  //   markingPrice: 30,
  //   sellPrice: 30,
  // },
  // {
  //   priceType: "儿童票",
  //   costPrice: 20,
  //   competitorPrice: 20,
  //   markingPrice: 20,
  //   sellPrice: 0.01,
  // },
  // {
  //   priceType: "老年票",
  //   costPrice: 10,
  //   competitorPrice: 10,
  //   markingPrice: 10,
  //   sellPrice: 10,
  // },
]);
const priceTemplateTemplate = {
  priceType: "",
  withBedFlag: 0,
  competitorPrice: null,
  markingPrice: null,
  sellPrice: null,
};

const selectWeek = ref([0, 1, 2, 3, 4, 5, 6]);
const selectOperate = ref("add");
const selectDate = ref();
const pickerOptions = [
  {
    text: "一个月",
    value() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
      return [end, start];
    },
  },
  {
    text: "三个月",
    value() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
      return [end, start];
    },
  },
  {
    text: "半年",
    value() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() + 3600 * 1000 * 24 * 182);
      return [end, start];
    },
  },
  {
    text: "一年",
    value() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() + 3600 * 1000 * 24 * 365);
      return [end, start];
    },
  },
];
const disabledDate = (date) => {
  return (
    date.getTime() < Date.now() - 3600 * 1000 * 24 ||
    date.getTime() > Date.now() + 3600 * 1000 * 24 * 365
  );
};
const weeks = [
  { id: 1, name: "周一" },
  { id: 2, name: "周二" },
  { id: 3, name: "周三" },
  { id: 4, name: "周四" },
  { id: 5, name: "周五" },
  { id: 6, name: "周六" },
  { id: 0, name: "周日" },
];

const operate = [
  { id: "clear", name: "清空" },
  { id: "modify", name: "覆盖" },
  { id: "add", name: "添加" },
];

watch(
  () => calendarSwitch.value,
  (val) => {
    emit("calendarSwitch", val);
  }
);

function getOperate() {
  let data = {
    date: selectDate.value,
    template: { price: priceTemplateRef.value.getValue(), other: {} },
    week: selectWeek.value,
    operate: selectOperate.value,
  };
  for (const key in baseData) {
    data.template.other[key] = baseData[key];
  }
  return data;
}

function isNotNull(value) {
  if (value != null && value != undefined) {
    if (value.length) {
      return value.length > 0;
    } else {
      return true;
    }
  } else {
    return false;
  }
}

function chackBaseData() {
  if (baseData.singleRoomPrice == null) {
    msg.error("请填写单房差");
    return false;
  }
  let num = 0;
  chackBaseKey.forEach((item) => {
    if (baseData[item]) {
      num += 1;
    }
  });
  if (num < chackBaseKey.length && num > 0) {
    msg.error("请完善日期价格设置");
    return false;
  }
  if (num == chackBaseKey.length) {
    if (parseInt(baseData.stockNum) <= 0) {
      msg.error("库存需要大于0");
      return false;
    }
    if (
      parseInt(baseData.orderPeopleNum) < parseInt(baseData.packagePeopleNum)
    ) {
      msg.error("最大预定人数需要大于最低预定人数");
      return false;
    }
  }
  return true;
}

function validate() {
  if (!chackBaseData()) {
    return false;
  }
  for (const price of priceTemplateRef.value.getValue()) {
    for (const templateKey in price) {
      if (!isNotNull(price[templateKey])) {
        msg.error("请选择完善价格");
        return false;
      }
    }
  }
  return true;
}

function execute() {
  const data = {
    date: selectDate.value,
    template: { price: priceTemplateRef.value.getValue(), other: {} },
    week: selectWeek.value,
    operate: selectOperate.value,
  };

  for (const key in baseData) {
    data.template.other[key] = baseData[key];
  }
  if (selectOperate.value != "clear") {
    if (!chackBaseData()) {
      return;
    }
    for (const price of data.template.price) {
      for (const templateKey in price) {
        if (!isNotNull(price[templateKey])) {
          msg.error("请选择完善价格");
          return;
        }
      }
    }

    if (data.date == null) {
      msg.error("请选择时间范围");
      return;
    }

    if (data.week.length <= 0) {
      msg.error("请选择星期");
      return;
    }
  }
  emit("execute", data);
}

function addTemplate() {
  emit("checkOperateChange", (res) => {
    if (res) {
      var data = {};
      for (const key in priceTemplateTemplate) {
        data[key] = priceTemplateTemplate[key];
      }
      priceTemplateRef.value.addData(data);
    } else {
      msg.error("已经生成了日期价格数据，请先清空后再添加");
    }
  });
}

function delTemplate(index) {
  emit("checkOperateChange", (res) => {
    if (res) {
      priceTemplateRef.value.getReactiveValue().splice(index, 1);
    } else {
      msg.error("已经生成了日期价格数据，请先清空后再删除");
    }
  });
}

function importData(data) {
  for (const key in baseData) {
    for (const p of data.price) {
      delete p[key]
    }
  }
  priceTemplate.value = data.price;
}

function resetData() {
  baseDataFormRef.value.resetFields();
  for (const key in baseData) {
    baseData[key] = null;
  }
  priceTemplate.value = [];
  priceTemplateRef.value.clear();
}

function getData() {
  return { price: priceTemplateRef.value.getValue() };
}

defineExpose({
  getOperate,
  importData,
  resetData,
  getData,
  chackBaseKey,
  validate,
});
</script>

<style  lang="scss">
.calendar_switch {
  margin-right: 40px;
}

.travel_price_operate {
  .el-table th.el-table__cell {
    padding: 6px 0;
  }

  .el-table .el-table__cell {
    padding: 4px;
  }

  .dashed_but {
    margin: 5px 10px;
    padding: 5px;
  }

  .operate_layout {
    margin: 10px 10px 0 10px;

    //   display: flex;
    //   flex-direction: row;
    .picker {
      width: 250px;
    }

    .operate_item {
      margin-top: 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
  }
}
</style>